<?php

namespace app\cps\service;

use app\model\Money;
use app\model\PayRecord;
use app\model\User;
use app\model\Link;
use app\model\OfficialAccounts;
use app\model\Videos;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use app\model\DailyDeliveryData;
use think\facade\Db;
use app\common\Common;
use app\model\LaunchAccount;
use app\model\ResponsibilityPerson;
use app\common\Error;

class OrderService
{
    private $payRecordModel;
    private $userModel;
    private $linkModel;
    private $officialAccountsModel;
    private $videosModel;
    private $dailyDeliveryDataModel;
    private $launchAccountModel;
    private $responsibilityPersonModel;

    public function __construct(PayRecord $payRecordModel, User $userModel, Link $linkModel, OfficialAccounts $officialAccountsModel, Videos $videosModel, DailyDeliveryData $dailyDeliveryDataModel, LaunchAccount $launchAccountModel, ResponsibilityPerson $responsibilityPersonModel)
    {
        $this->payRecordModel = $payRecordModel;
        $this->userModel = $userModel;
        $this->linkModel = $linkModel;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->videosModel = $videosModel;
        $this->dailyDeliveryDataModel = $dailyDeliveryDataModel;
        $this->launchAccountModel = $launchAccountModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
    }

    // 获取订单列表
    public function getOrderList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $linkId = $params['link_id'];
        $where[] = ['link_id', '=', $linkId];

        // 商户单号
        if (!empty($params['order_no'])) {
            $where[] = ['order_no', 'like',  $params['order_no'] . '%'];
        }
        // 用户ID
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }

        // 充值金额
        if (!empty($params['total_fee'])) {
            $where[] = ['total_fee', '=', $params['total_fee']];
        }
        // 支付状态
        if (isset($params['status']) && is_numeric($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        // 支付时间
        if (!empty($params['start_time'])) {
            $where[] = ['pay_time', '>=', strtotime($params['start_time'])];
        }
        if (!empty($params['end_time'])) {
            $where[] = ['pay_time', '<=', strtotime($params['end_time'] . ' 23:59:59')];
        }

        // 下单时间
        if (!empty($params['order_time'])) {
            $consumeDate = str_replace('-', '', $params['order_time']);
            $where[] = ['consume_date', '=', $consumeDate];
        }
        // 短剧
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        // 计划ID
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }

        // 激活时间
        if (!empty($params['activation_start_time'])) {
            $where[] = ['activation_time', '>=', $params['activation_start_time']];
        }
        if (!empty($params['activation_end_time'])) {
            $where[] = ['activation_time', '<=', $params['activation_end_time']];
        }

        $data = $this->payRecordModel->getPagingDataByWhere($where, $page, $limit, 'id, uid, order_no, wechat_order_no, type, total_fee, status, created_at, pay_time, link_id, video_id, advertiser_id, activation_time');

        $uids = $videoIds = [];
        if ($data['data']) {
            foreach ($data['data'] as $key => $value) {
                $uids[] = $value['uid'];
                $videoIds[] = $value['video_id'];
            }

            // 用户注册时间
            $userData = $this->userModel->getBatchDataByWhere(['id' => $uids], 'id, register_date, created_at');
            $users = array_column($userData, 'created_at', 'id');

            // 公众号名称
            $officialAccountId = $this->linkModel->getInfoByWhere(['id' => $linkId], 'official_account_id')['official_account_id'];
            $officialAccountName = $this->officialAccountsModel->getInfoById($officialAccountId, 'name')['name'];

            // 短剧名称
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['user_created_at'] = empty($users[$item['uid']]) ? '' : $users[$item['uid']];
                $data['data'][$key]['official_account_name'] = $officialAccountName;
                $data['data'][$key]['video_name'] = empty($videos[$item['video_id']]) ? '' : $videos[$item['video_id']];
            }
        }

        return $data;
    }

    // 链接订单详情统计
    public function linkOrderDetailListSumRecharge($params)
    {
        $linkId = $params['link_id'];
        $where[] = ['link_id', '=', $linkId];

        // 商户单号
        if (!empty($params['order_no'])) {
            $where[] = ['order_no', 'like',  $params['order_no'] . '%'];
        }
        // 用户ID
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }

        // 充值金额
        if (!empty($params['total_fee'])) {
            $where[] = ['total_fee', '=', $params['total_fee']];
        }
        // 支付状态
        if (isset($params['status']) && is_numeric($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        // 支付时间
        if (!empty($params['start_time'])) {
            $where[] = ['pay_time', '>=', strtotime($params['start_time'])];
        }
        if (!empty($params['end_time'])) {
            $where[] = ['pay_time', '<=', strtotime($params['end_time'] . ' 23:59:59')];
        }

        // 下单时间
        if (!empty($params['order_time'])) {
            $consumeDate = str_replace('-', '', $params['order_time']);
            $where[] = ['consume_date', '=', $consumeDate];
        }
        // 短剧
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }

        // 计划ID
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }

        // 激活时间
        if (!empty($params['activation_start_time'])) {
            $where[] = ['activation_time', '>=', $params['activation_start_time']];
        }
        if (!empty($params['activation_end_time'])) {
            $where[] = ['activation_time', '<=', $params['activation_end_time']];
        }

        $data = $this->payRecordModel->getSumPrice($where);
        return ['total_price' => $data];
    }

    // 获取历史数据
    public function getHistoryDataList($params)
    {
        $linkId = $params['link_id'];
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [
            ['link_id', '=', $linkId]
        ];
        if (!empty($params['start_date'])) {
            $startData = str_replace('-', '', $params['start_date']);
            $where[] = ['date', '>=', $startData];
        }

        if (!empty($params['end_date'])) {
            $endData = str_replace('-', '', $params['end_date']);
            $where[] = ['date', '<=', $endData];
        }

        $statisticalData = $this->dailyDeliveryDataModel->getPagingDataByWhere($where, $page, $limit, 'date, current_recharge, total_recharge, new_recharge_number, new_user_number, cost, activation_user_num, conversion_number, actual_cost, recharge_number');
        return $statisticalData;
    }

    // 历史数据统计
    public function getHistoryDataSum($params)
    {
        $where[] = ['link_id', '=', $params['link_id']];
        if (!empty($params['start_date'])) {
            $where[] = ['date', '>=', str_replace('-', '', $params['start_date'])];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['date', '<=', str_replace('-', '', $params['end_date'])];
        }

        $statisticalData = $this->dailyDeliveryDataModel->getDataByWhere($where, 'date, current_recharge, total_recharge, new_recharge_number, new_user_number, cost, activation_user_num, conversion_number, actual_cost, recharge_number');
        $data = [
            'current_recharge' => 0,
            'total_recharge' => 0,
            'new_recharge_number' => 0,
            'new_user_number' => 0,
            'cost' => 0,
            'activation_user_num' => 0,
            'conversion_number' => 0,
            'actual_cost' => 0,
            'recharge_number' => 0
        ];

        foreach ($statisticalData as $key => $value) {
            $data['current_recharge'] += $value['current_recharge']; // 累计新充金额
            $data['total_recharge'] += $value['total_recharge']; // 累计金额
            $data['new_recharge_number'] += $value['new_recharge_number']; // 新充笔数
            $data['new_user_number'] += $value['new_user_number']; // 新充人数
            $data['cost'] += $value['cost']; // 累计成本
            $data['activation_user_num'] += $value['activation_user_num']; // 注册用户数
            $data['conversion_number'] += $value['conversion_number'];
            $data['actual_cost'] += $value['actual_cost'];
            $data['recharge_number'] += $value['recharge_number'];
        }

        $data['current_recharge'] = round($data['current_recharge'], 2);
        $data['total_recharge'] = round($data['total_recharge'], 2);
        $data['current_recharge'] = round($data['current_recharge'], 2);
        $data['cost'] = round($data['cost'], 2);
        $data['actual_cost'] = round($data['actual_cost'], 2);

        return $data;
    }

    // 订单明细列表
    public function getOrderDetailedList($params, $userInfo)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
        $where = [];

        // 非cps账号只获取当前的账户的数据
        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');
        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;

            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }

        $new_where = $this->getOrderListWhere($params);
        $where = array_merge($where, $new_where);

        $data = $this->payRecordModel->getPagingDataByWhere($where, $page, $limit, 'id, order_no, uid, type, total_fee, status, created_at, pay_time, link_id, official_account_id, video_id, advertiser_id, activation_time, device_type');

        if ($data['data']) {
            $uids = $officialAccountIds = $videoIds = [];
            foreach ($data['data'] as $value) {
                $uids[] = $value['uid'];
                $officialAccountIds[] = $value['official_account_id'];
                $videoIds[] = $value['video_id'];
            }

            if ($officialAccountIds) $officialAccountIds = array_unique($officialAccountIds);

            $userData = $officialAccountsData = $videoData = [];
            if ($uids) {
                $userInfo = $this->userModel->getBatchDataByWhere(['id' => $uids], 'id, created_at');
                $userData = array_column($userInfo, 'created_at', 'id');
            }
            if ($officialAccountIds) {
                $officialAccounts = $this->officialAccountsModel->getDataByWhere(['id' => $officialAccountIds], 'id, name');
                $officialAccountsData = array_column($officialAccounts, 'name', 'id');
            }
            if ($videoIds) {
                $videos = $this->videosModel->getDataByWhere(['id' => $videoIds], 'id, name');
                $videoData = array_column($videos, 'name', 'id');
            }

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['user_register_time'] = empty($userData[$value['uid']]) ? '' : $userData[$value['uid']];
                $data['data'][$key]['official_account_name'] = empty($officialAccountsData[$value['official_account_id']]) ? '' : $officialAccountsData[$value['official_account_id']];
                $data['data'][$key]['video_name'] = empty($videoData[$value['video_id']]) ? '' : $videoData[$value['video_id']];
                $data['data'][$key]['device_type_text'] = PayRecord::DEVICE_TYPE_ARR[$value['device_type']] ?? 'other';
            }
        }
        return $data;
    }

    // 订单导出
    public function getOrderDetailedExcel($params, $userInfo)
    {
        ini_set('memory_limit', '-1');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        // 非cps账号只获取当前的账户的数据
        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;

            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        }

        $new_where = $this->getOrderListWhere($params);
        $where = array_merge($where, $new_where);

        $data = $this->payRecordModel->getInfo($where, 'id, order_no, uid, type, total_fee, status, created_at, pay_time, link_id, official_account_id, video_id, advertiser_id, activation_time,device_type');
        if ($data) {
            $uids = $officialAccountIds = $videoIds = [];
            foreach ($data as $value) {
                $uids[] = $value['uid'];
                $officialAccountIds[] = $value['official_account_id'];
                $videoIds[] = $value['video_id'];
            }
            if ($officialAccountIds) $officialAccountIds = array_unique($officialAccountIds);

            if ($officialAccountIds) {
                $officialAccounts = $this->officialAccountsModel->getDataByWhere(['id' => $officialAccountIds], 'id, name');
                $officialAccountsData = array_column($officialAccounts, 'name', 'id');
            }
            if ($videoIds) {
                $videos = $this->videosModel->getDataByWhere(['id' => $videoIds], 'id, name');
                $videoData = array_column($videos, 'name', 'id');
            }
            if (!empty($data)) {
                $spreadsheet = new Spreadsheet();
                $worksheet = $spreadsheet->getActiveSheet();
                $worksheet->setCellValueByColumnAndRow(1, 1, 'ID');
                $worksheet->setCellValueByColumnAndRow(2, 1, '用户ID');
                $worksheet->setCellValueByColumnAndRow(3, 1, '链接ID');
                $worksheet->setCellValueByColumnAndRow(4, 1, '短剧名称');
                $worksheet->setCellValueByColumnAndRow(5, 1, '公众号名称');
                $worksheet->setCellValueByColumnAndRow(6, 1, '投放计划ID');
                $worksheet->setCellValueByColumnAndRow(7, 1, '订单号');
                $worksheet->setCellValueByColumnAndRow(8, 1, '支付类型');
                $worksheet->setCellValueByColumnAndRow(9, 1, '支付金额');
                $worksheet->setCellValueByColumnAndRow(10, 1, '添加时间');
                $worksheet->setCellValueByColumnAndRow(11, 1, '支付时间');
                $worksheet->setCellValueByColumnAndRow(12, 1, '激活时间');
                $worksheet->setCellValueByColumnAndRow(13, 1, '投手名称');
                $worksheet->setCellValueByColumnAndRow(14, 1, '设备类型');
                // 写入内容
                $line = 0;
                $arr = Money::TYPE_ARR;
                //设备类型
                $arrDeviceType = [1=>'ios',2=>'android',3=>'其它'];

                foreach ($data as $key => $value) {
                    $line = $key + 2;
                    $official_account_name = empty($officialAccountsData[$value['official_account_id']]) ? '' : $officialAccountsData[$value['official_account_id']];
                    $video_name = empty($videoData[$value['video_id']]) ? '' : $videoData[$value['video_id']];
                    //获取订单对应投手
                    $fzr_name = "-";
                    $fzr_info = Link::where('id',$value['link_id'])->find();
                    if($fzr_info){
                        $ts_info = ResponsibilityPerson::where('id',$fzr_info->responsibility_person_id)->find();
                        $fzr_name = $ts_info->name?$ts_info->name:"-";
                    }
                    $worksheet->setCellValueByColumnAndRow(1, $line, $value['id']);
                    $worksheet->setCellValueByColumnAndRow(2, $line, $value['uid']);
                    $worksheet->setCellValueByColumnAndRow(3, $line, $value['link_id']);
                    $worksheet->setCellValueByColumnAndRow(4, $line, $video_name);
                    $worksheet->setCellValueByColumnAndRow(5, $line, $official_account_name);
                    $worksheet->setCellValueExplicitByColumnAndRow(6, $line, $value['advertiser_id'], DataType::TYPE_STRING);
                    $worksheet->setCellValueExplicitByColumnAndRow(7, $line, $value['order_no'], DataType::TYPE_STRING);
                    $worksheet->setCellValueByColumnAndRow(8, $line, $arr[$value['type']] ?? '');
                    $worksheet->setCellValueByColumnAndRow(9, $line, $value['total_fee']);
                    $worksheet->setCellValueByColumnAndRow(10, $line, date('Y-m-d H:i:s', $value['created_at']));
                    $worksheet->setCellValueByColumnAndRow(11, $line, date('Y-m-d H:i:s', $value['pay_time']));
                    $worksheet->setCellValueByColumnAndRow(12, $line, $value['activation_time']);
                    $worksheet->setCellValueByColumnAndRow(13, $line, $fzr_name);
                    $worksheet->setCellValueByColumnAndRow(14, $line, $arrDeviceType[$value['device_type']]);
                }
                $filename = './订单明细'.date("Y-m-d").'.xlsx';
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="'.$filename.'"');
                header('Cache-Control: max-age=0');
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save('php://output');
                $spreadsheet->disconnectWorksheets();
                unset($spreadsheet);
                exit;
            }
        }
        return $data;
    }

    // 订单列表统计充值
    public function orderListSumRechare($params, $userInfo)
    {
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
        $where = [];

        // 非cps账号只获取当前的账户的数据
        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;

            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }

        $new_where = $this->getOrderListWhere($params);
        $where = array_merge($where, $new_where);

        $data = $this->payRecordModel->getSumPrice($where);
        $userNum = $this->payRecordModel->getPeopleNumber($where);
        return ['total_price' => $data, 'user_num' => $userNum];
    }

    //订单明细公共条件
    private function getOrderListWhere($params): array
    {
        $where = [];
        // 商户单号搜索
        if (!empty($params['order_no'])) {
            $where[] = ['order_no', 'like', $params['order_no'].'%'];
        }
        // 用户id搜索
        if (!empty($params['uid'])) {
            $where[] = ['uid', '=', $params['uid']];
        }
        // 充值金额搜索
        if (!empty($params['total_fee'])) {
            $where[] = ['total_fee', '=', $params['total_fee']];
        }
        // 支付状态搜索
        if (isset($params['status']) && is_numeric($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }
        // 下单时间搜索
        if (!empty($params['consume_date'])) {
            $consumeDate = str_replace('-', '', $params['consume_date']);
            $where[] = ['consume_date', '=', $consumeDate];
        }
        // 推广链接id搜索
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }
        // 订单来源
        if (!empty($params['source'])) {
            $where[] = ['source', '=', $params['source']];
        }
        // 短剧搜索
        if (!empty($params['video_id'])) {
            $where[] = ['video_id', '=', $params['video_id']];
        }
        // 支付类型
        if (!empty($params['type'])) {
            $where[] = ['type', '=', $params['type']];
        }
        // 投放计划ID
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }
        // 激活时间
        if (!empty($params['activation_start_time'])) {
            $where[] = ['activation_time', '>=', $params['activation_start_time']];
        }
        if (!empty($params['activation_end_time'])) {
            $where[] = ['activation_time', '<=', $params['activation_end_time']];
        }
        // 支付时间
        if (!empty($params['pay_start_time'])) {
            $where[] = ['pay_time', '>=', strtotime($params['pay_start_time'])];
        }
        if (!empty($params['pay_end_time'])) {
            $where[] = ['pay_time', '<=', strtotime($params['pay_end_time'])];
        }
        if (!empty($params['device_type'])) {
            $where[] = ['device_type', '=', $params['device_type']];
        }
        return $where;
    }

    // 获取链接的LTV数据
    public function getLinkDailyRechargeDetails($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $linkId = $params['link_id'];

        $data = $this->dailyDeliveryDataModel->getPagingDataByWhere(['link_id' => $linkId], $page, $limit, 'date, activation_user_num, actual_cost, current_recharge, current_recovery, total_recharge, conversion_number, conversion_cost, per_capita_contribution');

        if ($data['data']) {
            foreach ($data['data'] as $key => $value) {
                $thisDay = substr($value['date'], 0, 4) . '-' . substr($value['date'], 4, 2) . '-' . substr($value['date'], 6, 2);
                for ($i = 1; $i < 8; $i++) {
                    $moneyDate[] = date('Ymd', strtotime($thisDay) + $i * 86400);
                }

                $payRecordData = $this->payRecordModel->getInfo(['link_id' => $linkId, 'consume_date' => $moneyDate, 'status' => 1, 'activation_date' => $value['date']], 'consume_date, total_fee');

                $ltvDate = [
                    '2_day' => 0,
                    '3_day' => 0,
                    '4_day' => 0,
                    '5_day' => 0,
                    '6_day' => 0,
                    '7_day' => 0,
                    '8_day' => 0
                ];

                $data['data'][$key]['date'] = $thisDay;
                $data['data'][$key]['total_recovery'] = empty($value['actual_cost']) || empty($value['total_recharge']) || $value['actual_cost'] == '0.0' ? '0%' : round($value['total_recharge'] / $value['actual_cost'] * 100, 2) . '%';

                if ($payRecordData) {
                    foreach ($payRecordData as $k => $val) {
                        if ($val['consume_date'] == date('Ymd', strtotime($thisDay) + 1 * 86400)) {
                            $ltvDate['2_day'] += $val['total_fee'];
                        }
                        if ($val['consume_date'] == date('Ymd', strtotime($thisDay) + 2 * 86400)) {
                            $ltvDate['3_day'] += $val['total_fee'];
                        }
                        if ($val['consume_date'] == date('Ymd', strtotime($thisDay) + 3 * 86400)) {
                            $ltvDate['4_day'] += $val['total_fee'];
                        }
                        if ($val['consume_date'] == date('Ymd', strtotime($thisDay) + 4 * 86400)) {
                            $ltvDate['5_day'] += $val['total_fee'];
                        }
                        if ($val['consume_date'] == date('Ymd', strtotime($thisDay) + 5 * 86400)) {
                            $ltvDate['6_day'] += $val['total_fee'];
                        }
                        if ($val['consume_date'] == date('Ymd', strtotime($thisDay) + 6 * 86400)) {
                            $ltvDate['7_day'] += $val['total_fee'];
                        }
                        if ($val['consume_date'] == date('Ymd', strtotime($thisDay) + 7 * 86400)) {
                            $ltvDate['8_day'] += $val['total_fee'];
                        }
                    }
                }
                $data['data'][$key]['2_day'] = round($ltvDate['2_day'], 2);
                $data['data'][$key]['3_day'] = round($ltvDate['3_day'], 2);
                $data['data'][$key]['4_day'] = round($ltvDate['4_day'], 2);
                $data['data'][$key]['5_day'] = round($ltvDate['5_day'], 2);
                $data['data'][$key]['6_day'] = round($ltvDate['6_day'], 2);
                $data['data'][$key]['7_day'] = round($ltvDate['7_day'], 2);
                $data['data'][$key]['8_day'] = round($ltvDate['8_day'], 2);
            }
        }
        return $data;
    }

    // 获取分销商链接LTV数据
    public function getDistributionLtvData($params)
    {
        $page = $params['page'] ?? 1;
        $data = $this->payRecordModel->getInfo(['link_id' => $params['link_id'], 'status' => 1], 'consume_date, activation_date, uid, total_fee', 'activation_date desc');

        $payData = [];
        foreach ($data as $value) {
            $payData[$value['activation_date']][] = $value;
        }
        $activationDate = array_column($data, 'activation_date');
        $activationDates = array_unique($activationDate);

        $date = [];
        foreach ($activationDates as $value) {
            $date[] = $value;
        }

        $total = count($date); // 总数
        $totalPage = ceil($total / 10); // 总页数

        $start = $page == 1 ? 0 : ($page - 1) * 10 - 1;
        $queryDate = [];
        foreach ($date as $key => $value) {
            if ($start <= $key && $key <= $start + 10) {
                $queryDate[] = $value;
            }
        }

        // user
        $length = count($queryDate);
        $result = [];

        if ($length != 0) {
            $userWhere = [
                ['link_id', '=', $params['link_id']],
                ['activation_time', '<=', date('Y-m-d H:i:s', strtotime($queryDate[0] . ' 23:59:59'))],
                ['activation_time', '>=', date('Y-m-d H:i:s', strtotime($queryDate[$length - 1]))],
            ];
            $userData = $this->userModel->getBatchDataByWhere($userWhere, 'id, activation_time');

            $user = [];
            foreach ($userData as $key => $value) {
                $user[date('Ymd', strtotime($value['activation_time']))][] = $value['id'];
            }

            foreach ($queryDate as $key => $value) {
                $currentRecharge = 0; // 当期充值
                $totalRecharge = 0; // 累计充值
                $twoDayRecharge = 0;
                $threeDayRecharge = 0;
                $fourDayRecharge = 0;
                $fiveDayRecharge = 0;
                $rechargePeopleNum = 0; // 充值人数
                $perCapita = 0; // 人均贡献

                if (!empty($payData[$value])) {
                    $userNum = [];
                    foreach ($payData[$value] as $item) {
                        if ($item['consume_date'] == $value) {
                            $currentRecharge += $item['total_fee'];
                        }
                        $totalRecharge += $item['total_fee'];

                        $userNum[] = $item['uid'];

                        // 第二天充值
                        if ($item['consume_date'] == date('Ymd', strtotime($value) + 86400)) {
                            $twoDayRecharge += $item['total_fee'];
                        }
                        // 第三天充值
                        if ($item['consume_date'] == date('Ymd', strtotime($value) + 86400 * 2)) {
                            $threeDayRecharge += $item['total_fee'];
                        }
                        // 第四天充值
                        if ($item['consume_date'] == date('Ymd', strtotime($value) + 86400 * 3)) {
                            $fourDayRecharge += $item['total_fee'];
                        }
                        // 第五天充值
                        if ($item['consume_date'] == date('Ymd', strtotime($value) + 86400 * 4)) {
                            $fiveDayRecharge += $item['total_fee'];
                        }

                        $rechargePeopleNum = count(array_unique($userNum));
                    }
                }

                $result[] = [
                    'date' => substr($value, 0, 4) . '-' . substr($value, 4, 2) . '-' . substr($value, 6, 2),
                    'activation_user_num' => isset($user[$value]) ? count($user[$value]) : 0,
                    'current_recharge' => round($currentRecharge, 2),
                    'total_recharge' => round($totalRecharge, 2),
                    'recharge_people_num' => $rechargePeopleNum,
                    'per_capita' => empty($rechargePeopleNum) ? 0 : round($totalRecharge / $rechargePeopleNum, 2),
                    'two_day_recharge' => round($twoDayRecharge, 2),
                    'three_day_recharge' => round($threeDayRecharge, 2),
                    'four_day_recharge' => round($fourDayRecharge, 2),
                    'five_day_recharge' => round($fiveDayRecharge, 2)
                ];
            }
        }
        return ['total' => $total, 'total_page' => $totalPage, 'data' => $result];
    }

    // 分销商订单列表
    public function getDistributionOrderList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $info = $this->responsibilityPersonModel->getInfoByWhere(['token' => $params['token']], 'id');
        if (empty($info)) {
            return ['message' => Error::TOKEN_ERROR];
        }

        $pitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $info['id']], 'id');
        $pitcherIds = array_column($pitcher, 'id');

        if (empty($pitcherIds)) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        if (!empty($params['pitcher_id']) && !in_array($params['pitcher_id'], $pitcherIds)) {
            return ['message' => Error::PITCHER_ID_PARAMATER_ERROR];
        }

        if (!empty($params['pitcher_id'])) {
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $params['pitcher_id']], 'id, video_id, remark, responsibility_person_id');
        } else {
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $pitcherIds], 'id, video_id,remark, responsibility_person_id');
        }

        $linkIds = array_column($linkData, 'id');

        if (empty($linkIds)) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $where[] = ['status', '=', 1];
        $where[] = ['link_id', 'in', $linkIds];

        // 支付时间
        if (!empty($params['start_date'])) {
            $where[] = ['pay_time', '>=', strtotime($params['start_date'])];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['pay_time', '<=', strtotime($params['end_date'])];
        }

        $data = $this->payRecordModel->getPagingDataByWhere($where, $page, $limit, 'id, uid, link_id, video_id, order_no, type, total_fee, pay_time, advertiser_id, activation_time, device_type, source, pay_merchant');

        $uids = $videoIds = [];
        if ($data['data']) {

            $uids = array_column($data['data'], 'uid');
            $videoIds = array_column($data['data'], 'video_id');

            $linkVideoArray = array_column($linkData, 'video_id', 'id');
            $linkVideoIds = array_column($linkData, 'video_id');

            $linkVideoData = $this->videosModel->getDataByIds($linkVideoIds, 'id, name');
            $linkVideoIdAndName = array_column($linkVideoData, 'name', 'id');

            // 用户注册时间
            // by update huangxiaoshan at 2023/07/27 新增一个用户注册时间字段快鱼分销商需要
            $userData = $this->userModel->getBatchDataByWhere(['id' => $uids], 'id, ip, ua, open_id, clickid,created_at');
            $users = array_column($userData, NULL, 'id');

            // 短剧名称
            $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
            $videos = array_column($videoData, 'name', 'id');

            // by huangxiaoshan add 2023-07-21
            $tmp_link_data = array_column($linkData,'remark','id');
            // end

            // by huangxiaoshan add 2023-07-27 快鱼分销商要求新增投手ID
            $responsibility_person_id_arr = array_column($linkData,'responsibility_person_id','id');
            // end

            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['pay_time'] = empty($item['pay_time']) ? '' : date('Y-m-d H:i:s', $item['pay_time']);
                $data['data'][$key]['video_name'] = empty($videos[$item['video_id']]) ? '' : $videos[$item['video_id']];
                $data['data'][$key]['advertiser_id'] = empty($item['advertiser_id']) ? '' : $item['advertiser_id'];
                $data['data'][$key]['ip'] = empty($users[$item['uid']]['ip']) ? '' : $users[$item['uid']]['ip'];
                $data['data'][$key]['ua'] = empty($users[$item['uid']]['ua']) ? '' : $users[$item['uid']]['ua'];
                $data['data'][$key]['open_id'] = empty($users[$item['uid']]['open_id']) ? '' : $users[$item['uid']]['open_id'];
                $data['data'][$key]['clickid'] = empty($users[$item['uid']]['clickid']) ? '' : $users[$item['uid']]['clickid'];

                $data['data'][$key]['link_video_name'] = empty($linkVideoIdAndName[$linkVideoArray[$item['link_id']]]) ? '' : $linkVideoIdAndName[$linkVideoArray[$item['link_id']]];
                $data['data'][$key]['remark'] = $tmp_link_data[$item['link_id']] ?? ''; // by add huangxiaoshan 2023-07-21
                $data['data'][$key]['register_time'] = empty($users[$item['uid']]['created_at']) ? '' : $users[$item['uid']]['created_at']; // by add huangxiaoshan at 2023/07/27
                $data['data'][$key]['responsibility_person_id'] = $responsibility_person_id_arr[$item['link_id']] ?? ''; // by add huangxiaoshan 2023/07/27
                $data['data'][$key]['device_type_text'] = PayRecord::DEVICE_TYPE_ARR[$item['device_type']] ?? 'other';
                $data['data'][$key]['source_text'] = PayRecord::SOURCE_ARR[$item['source']] ?? '微信小程序支付';
                $data['data'][$key]['is_virtual_payment'] = $item['pay_merchant'] == PayRecord::PAY_MERCHANT_VIRTUALPAYMENT ? 1 : 0;
            }
        }

        return $data;
    }
}